package com.project.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.Reader;
import java.lang.reflect.Field;

@Component
@Aspect
public class ServiceAspect {
    private static SqlSessionFactory factory;
    static{
        try {
            Reader r = Resources.getResourceAsReader("mybatis.cfg.xml");
            factory = new SqlSessionFactoryBuilder().build(r);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Around("execution(* com.project.service..*.*(..))")
    public Object  around(ProceedingJoinPoint point){
        //得到session
        SqlSession session = factory.openSession();
        //得到目标对象
        Object target = point.getTarget();
        try {
            //得到目标对象的属性列表
            Field[] fieldArray = target.getClass().getDeclaredFields();
            for (Field f : fieldArray) {
                if (f.getType().isInterface()) {//判断属性是否为接口
                    //得到mapper接口实现类对象
                    Object mapper = session.getMapper(f.getType());
                    f.setAccessible(true);
                    //将目标对象的接口属性，赋为mapper对象
                    f.set(target, mapper);
                }
            }
            //执行目标对象的目标方法
            Object returnObj = point.proceed();
            //提交事务
            session.commit();

            return returnObj;
        }catch (Throwable e){
            e.printStackTrace();
            session.rollback();
        }finally{
            session.close();
        }

        return null;
    }
}
